﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAL.EstRec;
using System.IO;
using System.Data;

namespace BAL.EstRec
{ 
    public class CierreConsolidacion
    {
        private string UnidVer { get; set; }
        private string RutaLocal;
        private string RutaServer;
        private BgtVersion BgtDatos;
        private AppConfs ac;

        public CierreConsolidacion(string UnidVer,AppConfs conf)
        {
            this.UnidVer = UnidVer;
            BgtDatos = new BgtVersion();
            BgtDatos.unid = long.Parse(UnidVer);
            this.ac = conf;
        }

        public void MetodoConsolida() {

            if (setConsolidate()) {
                BgtDatos.isConsolidated= publicarArchivo();
            }
        }

        private bool setConsolidate()
        {

            try
            {
                SrvDB.ExecuteNonQuery("EXEC SP_SET_CONSOLIDATED @VERSION = " + UnidVer);
                return true;
            }
            catch (Exception Ex)
            {
                System.Windows.MessageBox.Show("Error al consolidar: " + Ex.Message);
                return false;
            }
        }

        public bool getConsolidate()
        {
            try
            {
                DataTable dt = new DataTable();

                dt = SrvDB.ExecuteQuery("EXEC SP_GET_CONSOLIDATED @VERSION = " + UnidVer);

                if (dt.Rows[0][0].ToString() == "True")
                    return true;
                else
                    return false;
            }
            catch (Exception Ex)
            {
                System.Windows.MessageBox.Show("Versión ya consolidada");
                return false;
            }
        }

        private bool publicarArchivo() {

            try
            {
                StreamWriter sw = new StreamWriter(ac.cnf.CierreConsolidacionLocal + UnidVer + ".txt", false, System.Text.Encoding.Default);
                sw.WriteLine("1");

                sw.Close();
                sw.Dispose();

                File.Copy(ac.cnf.CierreConsolidacionLocal + UnidVer + ".txt", ac.cnf.CierreConsolidacionServer + UnidVer + ".txt", true);

                return true;
            }
            catch (Exception Ex) {

                System.Windows.MessageBox.Show(Ex.Message);
                return false;
            }
        }        
    }
}
